package com.yxinsur.imc.business.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.javaparser.utils.StringEscapeUtils;
import com.yxinsur.imc.business.service.impl.ImcRocketmqMessageServiceImpl;
import com.yxinsur.imc.business.service.impl.ImcTenantServiceImpl;
import com.yxinsur.imc.business.vo.PantheonVo;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.rocketMq.entity.PantheonChannel;
import com.yxinsur.imc.common.rocketMq.entity.PantheonChannelOrganization;
import com.yxinsur.imc.system.service.impl.SysOrgServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 接收信息
 */
@Component
@Slf4j
public class BusinessMqMessageListener implements MessageListener {
    @Autowired
    ImcTenantServiceImpl tenantService;
    @Autowired
    SysOrgServiceImpl sysOrgService;
    @Autowired
    ImcRocketmqMessageServiceImpl messageService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        log.info("接收到MQ消息 -- Topic:{}, tag:{},msgId:{} , Key:{}, body:{}",
                message.getTopic(),message.getTag(),message.getMsgID(),message.getKey(),new String(message.getBody()));
        //接收渠道信息 机构信息
        int count = 0;
        try {

            String tag = message.getTag();
            PantheonVo pantheonVo = JSON.parseObject(StringEscapeUtils.unescapeJava(new String(message.getBody())), PantheonVo.class);
            String type = pantheonVo.getType();
            JSONArray pantheonVoDatas = pantheonVo.getDatas();
            if(CollectionUtils.isEmpty(pantheonVoDatas)){
                throw new BusinessException("接收业务信息为null");
            }
            count = 0;
            if("CHANNEL_MSG".equals(tag)){
                List<PantheonChannel> channels = jsonToData(pantheonVoDatas, PantheonChannel.class);
                String channelSource = channels.get(0).getChannelSource();
                if("2".equals(channelSource)){
                    return Action.CommitMessage;
                }
                if("add".equals(type)){
                    count+=tenantService.addPantheon(channels);
                }else if("update".equals(type)){
                    count+=tenantService.updatePantheon(channels);
                }else if("delete".equals(type)){
                    count+=tenantService.deletePantheon(channels);
                }else{
                    throw new BusinessException("未接收到正确的操作类型");
                }
            }else if ("ORG_MSG".equals(tag)){
                List<PantheonChannelOrganization> organizations = jsonToData(pantheonVoDatas, PantheonChannelOrganization.class);
                String orglSource = organizations.get(0).getOrglSource();
                if("2".equals(orglSource)){
                    return Action.CommitMessage;
                }
                if("add".equals(type)){
                    count+=sysOrgService.addPantheon(organizations);
                }else if("update".equals(type)){
                    count+=sysOrgService.updatePantheon(organizations);
                }else if("delete".equals(type)){
                    count+=sysOrgService.deletePantheon(organizations);
                }else{
                    throw new BusinessException("未接收到正确的操作类型");
                }
            }else{
                return Action.CommitMessage;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return Action.ReconsumeLater;
        }finally {
            messageService.saveMessage(message);
        }
        if(count>0){
            return Action.CommitMessage;
        }
        return Action.ReconsumeLater;
    }

    public <T>List<T> jsonToData(JSONArray jsonArray, Class<T> clz){
        if (CollectionUtils.isEmpty(jsonArray)){
            return new ArrayList<T>();
        }
        List<T> result = new ArrayList<T>(jsonArray.size());
        jsonArray.forEach(element->{
            // 基础类型不可以转化为JSONObject，需要特殊处理
            if (element instanceof String
                    || element instanceof Number
                    || element instanceof Boolean
            ){
                result.add((T)element);
            }else {
                T t = JSONObject.toJavaObject((JSONObject)element, clz);
                result.add(t);
            }
        });
        return result;
    }


}
